/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package controller;

import com.jfinal.core.Controller;
import com.jfinal.core.JFinal;
import com.jfinal.plugin.activerecord.Db;
import com.jfinal.upload.UploadFile;
import java.io.File;
import java.util.List;
import model.Upfile;

/**
 *
 * @author Lx
 */
public class Upfilecontroller extends Controller {

    public void index() {
        List<Upfile> upfiles = Upfile.upfile.find("select * from file");
        setAttr("upfiles", upfiles);
        System.out.println("得到数据" + upfiles.size() + "条");
        render("list.jsp");
    }

    public void form() {
        Integer id = getParaToInt(0);
        if (id != null && id > 0) {
            setAttr("upfile", Upfile.upfile.findById(id));
        }
        render("form.jsp");
    }

    public void submit() {
        UploadFile file = getFile("file");
        Upfile upfile = getModel(Upfile.class, "upfile");
        if(file!=null){
        String path = JFinal.me().getConstants().getBaseUploadPath() + "/" + file.getFileName();
        upfile.put("src", path);
        upfile.save();
        }
        redirect("/upfile");
    }

    public void update() {
        UploadFile file = getFile("file");
        Integer id = getParaToInt("upfile.id");
        String oldsrc = Upfile.upfile.findById(id).get("src");
        String basepath = getSession().getServletContext().getRealPath("/");
        String oldurl = basepath + "/" + oldsrc;
        File name = new File(oldurl);
        if (name.exists()) {
            name.delete();
        }
        if(file!=null){
        String src = "/" + JFinal.me().getConstants().getBaseUploadPath() + "/" + file.getFileName();            
        Db.update("update file set title=?,src=?,remark=? where id=?", getPara("upfile.title"), src, getPara("upfile.remark"),id);
        }else{
            Upfile upfile=getModel(Upfile.class, "upfile");
            upfile.update();
        }
        redirect("/upfile");
    }

    public void edit() {
        form();
    }

    public void del() {
        Integer id = getParaToInt(0);
        if (id != null && id > 0) {
            String src = Upfile.upfile.findById(id).get("src");
            String basepath = this.getSession().getServletContext().getRealPath("/");
            String url = basepath + "/" + src;
            File name = new File(url);
            System.err.println(url);
            name.delete();
            Upfile.upfile.deleteById(getPara());
            redirect("/upfile");
            if (name.exists()) {
                renderHtml("<script>alert('删除失败！');window.location='/upfile'</script>");
            } else {
                renderHtml("<script>window.location='/upfile'</script>");
            }
        }
    }
}
